package com.shenhaofeng.app.http;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;


/**
 * Created by Administrator on 2016/5/5.
 */
public class Headers {

    private String[] namesAndValues;


    public Headers(String[] namesAndValues) {
        this.namesAndValues = namesAndValues;
    }


    public String[] namesAndValues() {
        return Arrays.copyOf(namesAndValues, namesAndValues.length);
    }


    public static Headers create(String... namesAndValues) {
        return new Headers(namesAndValues);
    }


    /**
     * 获取指定位置的name
     *
     * @param index
     * @return
     */
    public String name(int index) {
        return namesAndValues[index];
    }


    public String value(int index) {
        return namesAndValues[index + 1];
    }


    /**
     * 获取name集合
     *
     * @return
     */
    public Set<String> names() {
        TreeSet<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        for (int i = 0, size = size(); i < size; i++) {
            result.add(name(i));
        }
        return Collections.unmodifiableSet(result);
    }


    /**
     * 获取字段值集
     *
     * @param name
     * @return
     */
    public Set<String> values(String name) {
        if (name == null) {
            return Collections.emptySet();
        }
        TreeSet<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        for (int i = 0, size = size(); i < size; i++) {
            if (name.equalsIgnoreCase(name(i))) {
                result.add(value(i));
            }
        }
        return result;
    }


    /**
     * 获取字段值
     *
     * @param name
     * @return
     */
    public String value(String name) {
        Set<String> values = values(name);
        Iterator<String> iterator = values.iterator();
        if (iterator.hasNext()) {
            return iterator.next();
        }
        return null;
    }


    /**
     * 字段数
     *
     * @return
     */
    public int size() {
        return namesAndValues.length / 2;
    }


    /**
     * 参数构建器
     */
    public static class Builder {
        List<String> keys = new ArrayList<>();

        List<String> values = new ArrayList<>();


        public Builder put(String key, String value) {
            keys.add(key);
            values.add(value);
            return this;
        }


        public Headers build() {
            int size = keys.size();
            String[] kv = new String[2 * size];
            for (int i = 0; i < size; i++) {
                kv[i * 2] = keys.get(i);
                kv[i * 2 + 1] = values.get(i);
            }
            return new Headers(kv);
        }
    }

}
